package es.mgil.whoWantsToBeAMillonaire.runnables;

import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Message;
import es.mgil.whoWantsToBeAMillonaire.handlers.GetAddressHandler;

public class GetAddressRunnable implements Runnable {
	public static final int GET_ADDRESS_ERROR_COORDINATES = 0;
	public static final int GET_ADDRESS_ERROR_CONNECTION = 1;
	public static final int GET_ADDRESS_OK = 2;
	public static final int GET_ADDRESS_NO_ADDRESS = 3;

	private Context context;
	private GetAddressHandler handler;
	private double longitude;
	private double latitude;

	public GetAddressRunnable(Context context) {
		this.context = context;
		this.handler = new GetAddressHandler(context);
	}

	@Override
	public void run() {
		try {
			// create a geocoder object to retrieve the address
			Geocoder geocoder = new Geocoder(context);
			List<Address> addresses = geocoder.getFromLocation(latitude,
					longitude, 1);
			if (!addresses.isEmpty()) {
				// get the first address retrieved
				Address a = addresses.get(0);
				StringBuilder address = new StringBuilder();
				if (a.getThoroughfare() != null
						|| a.getSubThoroughfare() != null) {
					// retrieve the street
					if (a.getThoroughfare() != null) {
						address.append(a.getThoroughfare());
					}
					// retrieve the number
					if (a.getSubThoroughfare() != null) {
						address.append(" ");
						address.append(a.getSubThoroughfare());
					}
					address.append("\n");
				}
				if (a.getLocality() != null || a.getPostalCode() != null) {
					// retrieve the locality
					if (a.getLocality() != null) {
						address.append(a.getLocality());
					}
					// retrieve the postal code
					if (a.getPostalCode() != null) {
						address.append(" (");
						address.append(a.getPostalCode());
						address.append(")");
					}
					address.append("\n");
				}
				if (a.getCountryName() != null) {
					// retrieve the country
					address.append(a.getCountryName());
				}

				// update the IU
				handler.sendMessage(Message.obtain(handler, GET_ADDRESS_OK,
						address.toString()));
			} else {
				// no address has been found
				handler.sendMessage(Message.obtain(handler,
						GET_ADDRESS_NO_ADDRESS));
			}
		} catch (IOException e) {
			// an error occurred with the connection
			handler.sendMessage(Message.obtain(handler,
					GET_ADDRESS_ERROR_CONNECTION));
		}
	}

	/**
	 * Retrieve the address
	 */
	public void getAddress(double longitude, double latitude) {
		if (longitude == 0 || latitude == 0) {
			// only do it if the location is set
			handler.sendMessage(Message.obtain(handler,
					GET_ADDRESS_ERROR_COORDINATES));
		} else {
			// store the longitude and latitude
			this.longitude = longitude;
			this.latitude = latitude;

			Thread thread = new Thread(this);
			thread.start();
		}
	}
}
